package com.wangjie.binarysearch;

/**
 * @author jieshao
 * @date 2022/4/18 11:33
 *
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 */
class Test02 {
    public int[] searchRange(int[] nums, int target) {
        int left = binarySearch(nums, target, true);
        int right = binarySearch(nums, target, false);
        return new int[]{left, right};
    }

    public int binarySearch(int[] nums, int target, boolean flag) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (flag) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (flag) {
            return (left >= nums.length || nums[left] != target) ? -1 : left;
        } else {
            return (right < 0 || nums[right] != target) ? -1 : right;
        }
    }
}